<?php
session_start();
require_once("../Structure/fonctions.php");

$PAGE_TITLE = "Mon Compte - Lolgames";
$CONTENT_INCLUDE = "compte.html";

if (isset($_SESSION["user_id"])) {
    $bdd = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_BASE);
	
	include("../Structure/updateUser.php");

    //------------------------------------------------------------------//
    //      Mes Informations                                            //
    //------------------------------------------------------------------//

    //  Modifie les informations du user
    if (isset($_POST["submit-info"])) {
        $nom = $_POST['nom'];
        $prenom = $_POST['prenom'];
        $email = $_POST['email'];
        $pseudo = $_POST['pseudo'];
        $password = sha1($_POST['password']);
        $password2 = sha1($_POST['password2']);

        if (strcmp($password, $password2) == 0) { //Test si les 2 pwd sont identiques
            $query = "SELECT  id  FROM    users
                  WHERE   pseudo = '".$pseudo."'
                    AND   pseudo <> '".$user["pseudo"]."' ;";
            $double = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
            if(mysqli_num_rows($double) != 0) {
                $error_info = "Pseudo";
            }
            $query = "SELECT  id  FROM    users
                  WHERE   email = '".$email."'
                    AND   email <> '".$user["email"]."' ;";
            $double2 = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
            if(mysqli_num_rows($double2) != 0) {
                if(mysqli_num_rows($double) != 0) {
                    $error_info = "Pseudo et e-mail";
                }
                else {
                    $error_info = "E-mail";
                }
            }

            if(!isset($error_info)) {
                $user["firstName"] = $prenom;
                $user["lastName"] = $nom;
                $user["pseudo"] = $pseudo;
                $user["email"] = $email;

                if (!empty($_POST['password'])) {
                    $query = "UPDATE  users
                          SET     pseudo = '".$pseudo."', password = '".$password."', lastName = '".$nom."', firstName = '".$prenom."', email = '".$email."'
                          WHERE   id = ".$_SESSION['user_id']." ;";
                    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
                }
                else {
                    $query = "UPDATE  users
                          SET     pseudo = '".$pseudo."', lastName = '".$nom."', firstName = '".$prenom."', email = '".$email."'
                          WHERE   id = ".$_SESSION['user_id']." ;";
                    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
                }
            }
        }
        else {
            $error_pwd = "Les mots de passe sont différent !";
        }


    }

    //  Modifie l'avatar depuis un lien internet
    if (isset($_POST["submit-image-url"])) {
        $avatar = $_POST["avatar"];

        if($imgId == 0)
        {
            $query = "INSERT INTO images (link, autorID, statusID)
                      VALUES      ('".$link."', ".$_SESSION["user_id"].", 1) ;";
            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

            $query = "UPDATE  users
                      SET     avatarID = LAST_INSERT_ID()
                      WHERE   id = ".$_SESSION['user_id']." ;";
            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
        }
        else
        {
            $query = "UPDATE  images
                      SET     link = '".$link."', statusID = 1
                      WHERE   id = ".$imgId." ;";

            $res = mysqli_query($bdd, $query);
        }
    }

    //  Modifie l'avatar depuis un fichier local
    if (isset($_POST["submit-image-upload"]) && $_FILES["avatar"]["error"] == 0) {
        if ($_FILES["avatar"]["size"] < 5242880 /*5 Mio*/ ) {
            $extensions_valides = array( '.jpg' , '.jpeg' , '.gif' , '.png' , '.bmp' );
            $extension_upload = strtolower(strrchr($_FILES["avatar"]["name"], '.'));
            if (in_array($extension_upload,$extensions_valides)) {
                $move = move_uploaded_file($_FILES["avatar"]["tmp_name"], LOCALROOT."img/avatar/".$_SESSION["user_id"].$extension_upload);
                if ($move) {

					$query = "SELECT avatarID FROM users
                              WHERE  id = ".$_SESSION['user_id'].";";
								
					$res = mysqli_query($bdd, $query);
					
					$row = mysqli_fetch_array($res);
					
					$imgId = $row['avatarID']; 
					$link = "img/avatar/".$_SESSION['user_id'].$extension_upload;
					
					if($imgId == 0)
					{
						$query = "INSERT INTO images (link, autorID, statusID)
							      VALUES      ('".$link."', ".$_SESSION["user_id"].", 1) ;";
						$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

						$query = "UPDATE  users
								  SET     avatarID = LAST_INSERT_ID()
								  WHERE   id = ".$_SESSION['user_id']." ;";
						$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
					}
					else
					{
						$query = "UPDATE  images
								  SET     link = '".$link."', statusID = 1
								  WHERE   id = ".$imgId." ;";
								  	  
						$res = mysqli_query($bdd, $query);
					}
                }
            }
        }
    }
	
    $query = "SELECT  u.statusID, roleID, pseudo, lastName, firstName, email, i.link, hireDate, i.statusID imgStatus 
			  FROM    users u
              JOIN    images i ON   u.avatarID = i.id
              WHERE   u.id = ".$_SESSION["user_id"]." ;";
    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));


    if(mysqli_num_rows($res) == 1) {
        $row = mysqli_fetch_array($res);
    }


    //------------------------------------------------------------------//
    //      Historique                                                  //
    //------------------------------------------------------------------//

    $query = "SELECT    a.id, a.autorID, u.pseudo autor, title, content, type, a.statusID, note, link, a.date, i.statusID imgStatus
              FROM      articles a
              JOIN      users u ON a.autorID = u.id
              JOIN      historics h ON a.id = h.articleID
              JOIN      images i ON a.imageID = i.id
              WHERE     viewerID = ".$_SESSION["user_id"]."
                AND     a.statusID = 1
              ORDER BY  h.date DESC;";
    $res_hist = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
	
	
	//------------------------------------------------------------------//
    //      Mes articles                                                //
    //------------------------------------------------------------------//
    $query = "SELECT  COUNT(*) nb, ROUND(AVG(note),1) moy
              FROM    articles
              WHERE   autorID = ".$_SESSION["user_id"]."
                AND   statusID = 1 ;";
    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

    if(mysqli_num_rows($res) == 1) {
        $row_art_stat = mysqli_fetch_array($res);
    }

    $query = "SELECT    a.id, title, content, type, a.statusID, note, link, date, i.statusID imgStatus
              FROM      articles a
              JOIN      images i ON a.imageID = i.id
              WHERE     a.autorID = ".$_SESSION["user_id"]."
              ORDER BY  date DESC;";
    $res_art = mysqli_query($bdd, $query) or die(mysqli_error($bdd));


	//------------------------------------------------------------------//
    //      Mes commentaires                                            //
    //------------------------------------------------------------------//
    $query = "SELECT  COUNT(*) nb, ROUND(AVG(note),1) moy
              FROM    comments
              WHERE   autorID = ".$_SESSION["user_id"]."
                AND   statusID = 1 ;";
    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

    if(mysqli_num_rows($res) == 1) {
        $row_com_stat = mysqli_fetch_array($res);
    }

    $query = "SELECT    a.id, title, c.content, c.statusID, c.note, c.date
              FROM      comments c
              JOIN      articles a ON c.articleID = a.id
              WHERE     c.autorID = ".$_SESSION["user_id"]."
                AND     c.statusID = 1
              ORDER BY  c.date DESC;";
    $res_com = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
	//------------------------------------------------------------------//
    //      Mes notes                                                   //
    //------------------------------------------------------------------//
    //  Pouces
    if(isset($_POST["note"])) {
        if(isset($_POST["comType"])) {
            $isCom = 1;
            $id = $_POST["comID"];
            $table = "comments";
        } else {
            $isCom = 0;
            $id = $_POST["id"];
            $table = "articles";
        }

        $query = "SELECT  id
                  FROM    notes
                  WHERE   autorID = ".$_SESSION["user_id"]."
                    AND   originID = ".$id."
                    AND   isComment = ".$isCom.";";
        $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

        if(mysqli_num_rows($res) == 1) {
            $note = mysqli_fetch_array($res);
            $query = "UPDATE  notes
                      SET     note = ".$_POST["note"].", date = SYSDATE()
                      WHERE   id = ".$note['id']." ;";
            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
        }
        else {
            $query = "INSERT INTO notes (autorID, originID, isComment, note, date)
                      VALUES      (".$_SESSION['user_id'].", ".$id.", ".$isCom.", ".$_POST["note"].", SYSDATE()) ;";
            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
        }

        $query = "UPDATE  ".$table."
                  SET     note = (SELECT  SUM(note) FROM notes
                                  WHERE   originID = ".$id."
                                  AND     isComment = ".$isCom.")
                  WHERE   id = ".$id." ;";

        $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
    }

    //Notes Articles
    $query = "SELECT    a.id, title, a.note note, n.note pouce, a.autorID, u.pseudo autor, a.date
              FROM      notes n
              JOIN      articles a ON n.originID = a.id
              AND       isComment = 0
              JOIN      users u ON a.autorID = u.id
              WHERE     n.autorID = ".$_SESSION["user_id"]."
                AND     a.statusID = 1
              ORDER BY  n.date DESC;";
    $res_note_art = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

    //Notes Commentaires
    $query = "SELECT    c.id, c.articleID, title, c.note note, n.note pouce, a.autorID, u.pseudo autor, c.content, c.date
              FROM      notes n
              JOIN      comments c ON n.originID = c.id
              AND       isComment = 1
              JOIN      articles a ON a.id = c.articleID
              JOIN      users u ON c.autorID = u.id
              WHERE     n.autorID = ".$_SESSION["user_id"]."
                AND     a.statusID = 1
                AND     c.statusID = 1
              ORDER BY  n.date DESC;";
    $res_note_com = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
}

include_once("../Structure/structure.php");

?>